from db import Db,make_password
from myJWT import MyJwt

class Login:
    def __init__(self,username,password):
        self.username = username
        self.password = password
        self.db = Db()
    def user_login(self):
        sql = " select * from `users` where username = '%s' and password = '%s' " % (self.username,make_password(self.password))
        res = self.db.get_one(sql)
        if res:
            myjwt = MyJwt()
            token = myjwt.encode_jwt({'id':res['id'],'username':res['username']})
            return {'code':200,'msg':'登录成功','username':res['username'],'token':token}
        else:
            return {'code':400,'msg':'你的用户名或密码错误'}
import redis
class Phone(Login):
    def __init__(self,phone,code):
        self.phone = phone
        self.code =code
        self.db = Db()
    def user_login(self):
        r = redis.Redis()
		# code_redis = r.get(self.phone)
        code_redis = r.get(self.phone)
        try:
            code_redis = code_redis.decode('utf-8')
        except Exception as e:
            pass
        if code_redis is None:
            return {'code':403,'msg':'你的验证码已经过期'}
        if self.code == code_redis:
            res = self.db.get_one(" select id,username from `users` where phone = '%s' " % self.phone)
            if res:
                return {'code':200,'msg':'登录成功',"id":res['id'],"username":res['username']}
            else:
                self.db.insert(" insert into `users` (`username`,`password`,`phone`) values ('%s','%s','%s') " % (self.phone,'',self.phone))
                res = self.db.get_one(" select id,username from `users` where phone = '%s' " % self.phone)
                return {'code':200,'msg':"登录成功","id":res['id'],"username":res['username']}
        else:
            return {'code':403,'msg':"您的验证码有误"}

        












            

